/**
 * tzdesk系统平台
 * tzupload
 * com.tz.core
 * LoginIntercetor.java
 * 创建人:hufanglei
 * 时间：2016年11月13日-下午9:51:18
 *
 */
package com.tz.core;

import com.tz.bean.AdminUser;
import com.tz.util.TmStringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.URLEncoder;

import static com.tz.util.TzConstant.SESSION_USER;

/**
 * 
 * LoginIntercetor
 * 创建人:hufanglei
 * 时间：
 * @version 1.0.0
 * 
 */
public class LoginIntercetor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//获取请求的路径 便于二维码的跳转
		String fullPath = request.getRequestURL() + request.getQueryString();
		System.out.println("fullPath ==== "+ request.getRequestURL());
		System.out.println("进来了吗..........");
		AdminUser user = (AdminUser) request.getSession().getAttribute(SESSION_USER);
		if(user!=null){
			return true;
		}else{
			//执行是一个ajax请求还是一个普通请求
			String requestType  =  request.getHeader("X-Requested-With");
			//如果是ajax请求
			if(TmStringUtils.isNotEmpty(requestType) && requestType.equalsIgnoreCase("XmlHttpRequest")) {
				response.getWriter().print("logout");
			}else{
				StringBuilder urlBuilder=new StringBuilder(request.getContextPath());
				urlBuilder.append("/login");
				if(request.getServletPath()!=null && !request.getServletPath().isEmpty()){
					urlBuilder.append("?returnUrl=");
					StringBuilder pathAndQuery=new StringBuilder(request.getContextPath());
					pathAndQuery.append(request.getServletPath());
					if(request.getQueryString()!=null && !request.getQueryString().isEmpty()){
						pathAndQuery.append("?");
						pathAndQuery.append(request.getQueryString());
					}
					urlBuilder.append(URLEncoder.encode(pathAndQuery.toString(), "UTF-8"));
				}
				response.sendRedirect(urlBuilder.toString());
			}
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("请求结束执行的方法..........");
		
	}
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("响应已经被渲染成功后执行的方法..........");
		
	}

}
